'use strict';

// 亚马逊
const puppeteer = require('puppeteer');
const fs = require('fs');

(async () => {
    const browser = await puppeteer.launch({
        headless: false
    });
    const page = await browser.newPage();
    await page.goto('https://www.amazon.co.jp/-/zh/dp/B002ANRMUQ/?_encoding=UTF8&pd_rd_w=Edq6r&content-id=amzn1.sym.faf9973e-4d8c-40ec-aca3-abae39351aba&pf_rd_p=faf9973e-4d8c-40ec-aca3-abae39351aba&pf_rd_r=8HQM84DHGBWJECNC9DCC&pd_rd_wg=HZHhh&pd_rd_r=e1eb8739-8fd1-4c45-ad71-2cbfd251dbd7&ref_=pd_hp_d_btf_pd_pss_gwp_d_0');
    await page.setViewport({
        width: 1920,
        height: 1080
    });

    // await autoScroll(page);
    //
    // await page.screenshot({
    //     path: '1.png',
    //     fullPage: true
    // });

    const productTitle = await page.$eval('#productTitle', el => el.textContent);
    const price = await page.$eval('.a-price-whole', el => el.textContent);

    // 将内容保存到文件
    fs.writeFileSync('output.txt', productTitle+"\n"+price);

    await browser.close();
})();

function autoScroll(page) {
    return page.evaluate(() => {
        return new Promise((resolve, reject) => {
            let totalHeight = 0;
            const distance = 100;
            const timer = setInterval(() => {
                const scrollHeight = document.body.scrollHeight;
                window.scrollBy(0, distance);
                totalHeight += distance;
                if (totalHeight >= scrollHeight) {
                    clearInterval(timer);
                    resolve();
                }
            }, 100);
        })
    });
}
